import { ref } from 'vue'
import { defineStore } from 'pinia'
import { loginAPI, registerAPI, getMessageAPI } from '@/api/user'
import { ElMessage } from 'element-plus'
import type { LoginResponse, RegisterResponse } from '@/types/api'

// 用户信息类型定义
export interface UserInfo {
  id?: number
  username?: string
  role?: string
  email?: string
  phone?: string
  avatar?: string
  nickname?: string
  bio?: string
  created_at?: string
  updated_at?: string
}

export const useAuthStore = defineStore(
  'auth',
  () => {
    const token = ref('')
    const userInfo = ref<UserInfo | null>(null) // 使用UserInfo类型

    const login = async (email: string, password: string) => {
      try {
        const response = await loginAPI(email, password) as unknown as LoginResponse
        // service.ts 的响应拦截器已经处理了错误，成功时直接返回 data
        token.value = response.token
        userInfo.value = response.user
        localStorage.setItem('token', response.token)
        localStorage.setItem('refresh_token', response.refresh_token)
        return { success: true }
      } catch (error) {
        console.error('登录失败:', error)
        return { success: false }
      }
    }

    const register = async (params: {
      username: string
      email: string
      password: string
      role: string
      phone: string
      real_name: string
    }) => {
      try {
        const response = await registerAPI(params) as unknown as RegisterResponse
        // service.ts 的响应拦截器已经处理了错误，成功时直接返回 data
        ElMessage.success('注册成功，请等待管理员审核')
        return { success: true }
      } catch (error) {
        console.error('注册失败:', error)
        return { success: false }
      }
    }

    const refreshUserInfo = async () => {
      // 实际项目中应该从API获取用户信息
    }

    function clearToken() {
      token.value = ''
      userInfo.value = null
      localStorage.removeItem('token')
      localStorage.removeItem('auth')
    }

    return { token, clearToken, login, register, userInfo, refreshUserInfo }
  },
  {
    persist: true,
  },
)
